'''
Created on Oct 15, 2014

@author: Juan C. Espinoza
@contact: juan.espinoza@jro.igp.gob.pe
'''
import json
from lisn_utils import GPSDateTime
from django.http import HttpResponse
from django.core.exceptions import ObjectDoesNotExist,MultipleObjectsReturned

from lisn_utils import AttrDict

from apps.stations.models import Station
from apps.instruments.models import InstrumentType, Instrument

def station(request):

    code = request.GET.get('code', '')
    itype = request.GET.get('instrument', '')    
    try:
        inst = Instrument.objects.select_related().get(code=code, itype__name=itype)
        ret = AttrDict(inst.__dict__).from_keys(['code', 'network', 'server', 'status', 'id', 'lisn_code', 'last_file'])
        ret['info'] = json.loads(inst.info)
        ret['station'] = inst.station.name
        ret['country'] = inst.station.country
        ret['last_file_date'] = inst.last_file_date.strftime('%Y-%m-%d %H:%M:%S')
        ret['fullname'] = '%s, %s' % (inst.station.name.upper(), inst.station.country.title())
        ret['latitude'] = inst.station.latitude
        ret['longitude'] = inst.station.longitude
        ret['error'] = False
    except (ObjectDoesNotExist, MultipleObjectsReturned) as e:
        ret = {'error': True}

    return HttpResponse(json.dumps(ret), content_type="application/json")
    
def stations(request):
    kwargs = {}
    if 'code' in request.GET:
        kwargs['code'] = request.GET['code']
    if 'instrument' in request.GET:
        kwargs['itype__name'] = request.GET['instrument']
    if 'country' in request.GET:
        kwargs['station__country'] = request.GET['country']
    if 'server' in request.GET:
        kwargs['server'] = request.GET['server']
    if 'network' in request.GET:
        if ',' in request.GET['network']:
            kwargs['network__in'] = request.GET['network'].split(',')
        else:
            kwargs['network'] = request.GET['network']
    sites = Instrument.objects.select_related().filter(**kwargs).iterator()
    new = []
    for site in sites:
        ret = AttrDict(site.__dict__).from_keys(['code', 'network', 'server', 'status', 'id', 'lisn_code', 'last_file'])
        ret['info'] = json.loads(site.info)
        ret['station'] = site.station.name
        ret['country'] = site.station.country
        if site.last_file_date is not None:
            ret['last_file_date'] = site.last_file_date.strftime('%Y-%m-%d %H:%M:%S')
        else:
            ret['last_file_date'] = ''
        ret['fullname'] = '%s, %s' % (site.station.name.upper(), site.station.country.title())
        ret['latitude'] = site.station.latitude
        ret['longitude'] = site.station.longitude
        ret['altitude'] = site.station.altitude
        ret['location'] = (site.station.latitude, site.station.longitude, site.station.altitude)
        new.append(ret)
    return HttpResponse(json.dumps(new), content_type="application/json")
    
def update(request, instrument, code):

    ret = {'error': False}
    #ret.update(request.GET)   
    try:
        inst = Instrument.objects.get(code=code, itype__name=instrument)        
        for key,value in request.GET.items():
            ret[key] = value
            if key==u'last_file_date':
                value = GPSDateTime(value).datetime
            setattr(inst, key, value)            
        inst.save()
    except (ObjectDoesNotExist, MultipleObjectsReturned) as e:
        ret['error'] =True
    
    return HttpResponse(json.dumps(ret), content_type="application/json")    
    
